package controller

import (
	"parking-lot-go-dingding/config"
	"parking-lot-go-dingding/model/dingtalk"

	"github.com/gin-gonic/gin"
)

func Home(c *gin.Context) {
	requestStruct := struct {
		Page     int    `json:"page"`
		ClassId  int    `json:"class_id"`
		Limit    int    `json:"limit"`
		Keywords string `json:"keywords"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		Fail(c, "json接收失败")
		return
	}

	if requestStruct.ClassId == 0 {
		Fail(c, "缺少参数")
		return
	}

	var err error

	dbSection := config.Cfg.Section("SYSTEM")
	imageUrl := dbSection.Key("IMAGE_URL").String()

	var dingtalkNewsStruct dingtalk.DingtalkNewsStruct
	news, err := dingtalkNewsStruct.List(requestStruct.ClassId, requestStruct.Keywords, requestStruct.Page, requestStruct.Limit)
	if err != nil {
		Fail(c, err.Error())
		return
	}

	//新闻返回
	newsReturn := make([]map[string]interface{}, 0)

	for _, v := range news {
		newsReturn = append(newsReturn, map[string]interface{}{
			"id":         v.Id,
			"title":      v.Title,
			"image_path": imageUrl + v.ImagePath,
			"introduce":  v.Introduce,
		})
	}

	//轮播图
	bannerReturn := make([]map[string]interface{}, 0)
	bannerReturn2 := make([]map[string]interface{}, 0)

	var dingtalkBannerStruct dingtalk.DingtalkBannerStruct
	banner, err := dingtalkBannerStruct.List(1)
	if err != nil {
		Fail(c, err.Error())
		return
	}
	for _, v := range banner {
		bannerReturn = append(bannerReturn, map[string]interface{}{
			"id":         v.Id,
			"image_path": imageUrl + v.ImagePath,
		})
	}

	banner2, err := dingtalkBannerStruct.List(2)
	if err != nil {
		Fail(c, err.Error())
		return
	}
	for _, v := range banner2 {
		bannerReturn2 = append(bannerReturn2, map[string]interface{}{
			"id":         v.Id,
			"image_path": imageUrl + v.ImagePath,
		})
	}

	Success(c,
		map[string]interface{}{
			"news":    newsReturn,
			"banner":  bannerReturn,
			"banner2": bannerReturn2,
		})

}
